package cn.stylefeng.guns.modular.demo.controller;

import cn.stylefeng.guns.dao.IGaiaProductBusinessService;
import cn.stylefeng.guns.dao.IGoodsService;
import cn.stylefeng.guns.dao.ISaleStockService;
import cn.stylefeng.guns.dao.entity.GaiaBatchInfo;
import cn.stylefeng.guns.dao.entity.Goods;
import cn.stylefeng.guns.dao.entity.SaleStock;
import cn.stylefeng.guns.dao.service.IGaiaBatchInfoService;
import cn.stylefeng.guns.modular.demo.excel.domain.asilikang.shenji.PeisongExcelVo;
import cn.stylefeng.guns.modular.demo.excel.listener.aslikang.shenji.SalePeisongListener;
import cn.stylefeng.guns.modular.demo.service.SyncService;
import cn.stylefeng.guns.modular.demo.service.TestBizService;
import cn.stylefeng.guns.util.ConfigUtil;
import cn.stylefeng.guns.util.RebateDateUtil;
import cn.stylefeng.roses.kernel.rule.annotation.BusinessLog;
import cn.stylefeng.roses.kernel.rule.enums.ResBizTypeEnum;
import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.kernel.scanner.api.annotation.ApiResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.GetResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.PostResource;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import static cn.stylefeng.guns.modular.demo.service.SyncService.SIMPLE_DATE_FORMAT1;

/**
 * 示例控制器
 *
 * @author fengshuonan
 * @since 2021/1/24 10:57
 */
@RestController
@ApiResource(name = "文件", path = "/file", resBizType = ResBizTypeEnum.BUSINESS)
@Slf4j
public class DemoController {

    private String filrUrl = "/usr/local/resource";
    @Resource
    private TestBizService testBizService;
    @Resource
    private ISaleStockService saleStockService;


    @Resource
    IGoodsService goodsService;
    @Resource
    private IGaiaProductBusinessService gaiaProductBusinessService;
    @Resource
    IGaiaBatchInfoService gaiaBatchInfoService;

//    @Resource
//    private MailTimer mailTimer;
//    @Resource
//    private YearMailTimer yearMailTimer;

    @Resource
    private SyncService syncService;

    @GetResource(name = "模板下载 1 进销存模板 2供应商模板 3采购计划模板", path = "/download", requiredLogin = false, requiredPermission = false)
    @ApiOperation("模板下载")
    @BusinessLog
    public void download(@RequestParam("fileName") Integer fileType, HttpServletResponse response) throws IOException {
        String fileName = "";
        if (Objects.equals(fileType, 1)) {
            fileName = "sale";
        }
        if (Objects.equals(fileType, 2)) {
            fileName = "supplier";
        }
        if (Objects.equals(fileType, 3)) {
            fileName = "plan";
        }
        if (Objects.equals(fileType, 4)) {
            fileName = "goods";
        }
        if (Objects.equals(fileType, -1)) {
            fileName = "peisong";
        }
        if (Objects.equals(fileType, -2)) {
            fileName = "kucun";
        }
        String fileAddress = ConfigUtil.getFileAddress();

        downloadExcel(response, fileAddress + fileName + ".xlsx", "导入模板.xlsx");
    }


    /**
     * 下载模板文件
     *
     * @param response
     * @param inFileName
     * @param outFileNam
     */
    public void downloadExcel(HttpServletResponse response, String inFileName, String outFileNam) {
        InputStream inputStream = null;
        try {
            response.reset();
            //设置输出文件格式
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(outFileNam.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            ServletOutputStream outputStream = response.getOutputStream();
            inputStream = new FileInputStream(inFileName);
            byte[] buff = new byte[1024];
            int length;
            while ((length = inputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, length);
            }
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {

                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("关闭资源出错" + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }

    @GetResource(name = "sync/stock111111", path = "/sync/stock/test1111", requiredLogin = false, requiredPermission = false)
    @ApiOperation("syncstocktest11111")
    public void synctesttttt(@RequestParam("time") String time) throws IOException {
        LocalDate dateTime = LocalDate.parse(time, RebateDateUtil.formatter);
        LocalDate now = LocalDate.now();
        syncService.calStock(now.getDayOfYear() - dateTime.getDayOfYear());
    }


    @PostResource(name = "sync/aslikang/initdata", path = "/sync/aslikang/initdata", requiredLogin = false, requiredPermission = false)
    @ApiOperation("阿斯利康基础销售数据生成")
    public ResponseData<String> syncTestAslikang(MultipartFile file) throws IOException {
        //todo 同步阿斯利康基础销售数据
        ArrayList<String> errorList = Lists.newArrayList();
        EasyExcel.read(file.getInputStream(), PeisongExcelVo.class, new SalePeisongListener(saleStockService, errorList, goodsService, testBizService, gaiaBatchInfoService,"w0crdxdq50ss")).sheet().doRead();
        return new SuccessResponseData<>(String.join(",", errorList));
    }

    @PostResource(name = "sync/aslikang/initdata22222", path = "/sync/aslikang/initdata22222", requiredLogin = false, requiredPermission = false)
    @ApiOperation("initdata22222")
    public ResponseData<String> initdata3333444() throws IOException {
        List<SaleStock> list = saleStockService.list(Wrappers.<SaleStock>lambdaQuery().eq(SaleStock::getBatchNo, "").eq(SaleStock::getTag, "w0crdxdq50ss"));
        for (SaleStock saleStock : list) {
            String batch = saleStock.getBatch();
            if (StringUtils.isEmpty(batch)) {
                continue;
            }
            Goods one = goodsService.getById(saleStock.getGoodsId());
            String commodityCode = one.getCommodityCode();

            List<GaiaBatchInfo> list1 = gaiaBatchInfoService.list(Wrappers.<GaiaBatchInfo>lambdaQuery()
                    .eq(GaiaBatchInfo::getBatBatchNo, batch)
                    .eq(GaiaBatchInfo::getBatProCode, commodityCode)
            );
            GaiaBatchInfo gaiaBatchInfo = list1.get(0);
            saleStock.setBatchNo(gaiaBatchInfo.getBatBatch());
            saleStockService.updateById(saleStock);
        }
        return new SuccessResponseData<>();
    }


    public static void main(String[] args) {
        LocalDate dateTime = LocalDate.parse("20240620", RebateDateUtil.formatter);
        LocalDate now = LocalDate.now();
        int day = now.getDayOfYear() - dateTime.getDayOfYear();
        System.out.println(day);
    }


    @GetResource(name = "楚立堂数据同步", path = "/sync/chuli", requiredLogin = false, requiredPermission = false)
    @ApiOperation("sync")
    public void syncChuli(@RequestParam("time") String time, @RequestParam("endTime") String endTime) throws IOException {
        LocalDate parse = LocalDate.parse(time, SIMPLE_DATE_FORMAT1);
        log.info("开始同步数据time={},endTime={}", time, endTime);

        while (true) {
            String format = parse.format(SIMPLE_DATE_FORMAT1);
            syncService.syncMaterialData(format);
//            syncService.syncTestData(format);
            if (format.equals(endTime)) {
                break;
            }
            parse = parse.plusDays(1);
        }
    }

    @GetResource(name = "syncamount", path = "/sync/amount", requiredLogin = false, requiredPermission = false)
    @ApiOperation("sync同步更新实际金额")
    public void syncAmount(@RequestParam("time") String time, @RequestParam("endTime") String endTime) throws IOException {
        log.info("开始同步数据time={},endTime={}", time, endTime);
        syncService.sysnc();
//        while (true) {
//            String format = parse.format(SIMPLE_DATE_FORMAT1);
//            syncService.syncAmount(format);
//            if (format.equals(endTime)) {
//                break;
//            }
//            parse = parse.plusDays(1);
//        }
    }

    @GetResource(name = "sync", path = "/sync", requiredLogin = false, requiredPermission = false)
    @ApiOperation("sync")
    public void sync(@RequestParam("time") String time, @RequestParam("endTime") String endTime) throws IOException {
        LocalDate parse = LocalDate.parse(time, SIMPLE_DATE_FORMAT1);
        log.info("开始同步数据time={},endTime={}", time, endTime);

        while (true) {
            String format = parse.format(SIMPLE_DATE_FORMAT1);
            syncService.syncMaterialData(format);
//            syncService.calStock(1);
//            syncService.syncTestData(format);
            if (format.equals(endTime)) {
                break;
            }
            parse = parse.plusDays(1);
        }
        //基础数据
//        syncService.syncData();
//        syncService.syncStoreData();
        //进销存数据
//        syncService.syncMaterialData("20240401");
//        syncService.syncMaterialData("20240402");
//        syncService.syncMaterialData("20240403");
//        syncService.syncMaterialData("20240404");
//        syncService.syncMaterialData("20240405");
//        syncService.syncMaterialData("20240406");
//        syncService.syncMaterialData("20240407");
//        syncService.syncMaterialData("20240408");
//        syncService.syncMaterialData("20240409");
//        syncService.syncMaterialData("20240410");
//        syncService.syncMaterialData("20240411");
//        syncService.syncMaterialData("20240412");
//        syncService.syncMaterialData("20240413");
//        syncService.syncMaterialData("20240414");
//        syncService.syncMaterialData("20240415");
//        syncService.syncMaterialData("20240416");
//        syncService.syncMaterialData("20240417");
//        syncService.syncMaterialData("20240418");
//        syncService.syncMaterialData("20240419");
//        syncService.syncMaterialData("20240420");
//        syncService.syncMaterialData("20240421");
//        syncService.syncMaterialData("20240422");
//        syncService.syncMaterialData("20240423");
//        syncService.syncMaterialData("20240424");
//        syncService.syncMaterialData("20240425");
//        syncService.syncMaterialData("20240426");
//        syncService.syncMaterialData("20240427");
//        syncService.syncMaterialData("20240428");
//        syncService.syncMaterialData("20240429");
//        syncService.syncMaterialData("20240430");
//        syncService.syncMaterialData("20240501");
//        syncService.syncMaterialData("20240502");
//        syncService.syncMaterialData("20240503");
//        syncService.syncMaterialData("20240504");
//        syncService.syncTestData(time);
//        syncService.syncTestData("20240402");
//        syncService.syncTestData("20240403");
//        syncService.syncTestData("20240404");
//        syncService.syncTestData("20240405");
//        syncService.syncTestData("20240406");
//        syncService.syncTestData("20240407");
//        syncService.syncTestData("20240408");

//        syncService.syncData("20240402");
//        syncService.syncData("20240403");
//        syncService.syncData("20240404");
//        syncService.syncData("20240405");
//        syncService.syncData("20240406");
//        syncService.syncData("20240407");
//        syncService.syncData("20240408");
//        syncService.syncData("20240409");
//        syncService.syncData("20240410");
//        syncService.syncData("20240411");
//        syncService.syncData("20240412");
//        syncService.syncData("20240413");
//        syncService.syncData("20240414");
//        syncService.syncData("20240415");
//        testBizService.generateSingleTestData(time);
    }

    @GetResource(name = "sync", path = "/sync/test", requiredLogin = false, requiredPermission = false)
    @ApiOperation("synctest")
    @BusinessLog
    public void syncTest(@RequestParam("time") String time) throws IOException {
        //基础数据
//        syncService.syncData();
//        syncService.syncStoreData();
        //进销存数据
//        syncService.syncTestData("20240401");
//        syncService.syncTestData("20240402");
//        syncService.syncTestData("20240403");
//        syncService.syncTestData("20240404");
//        syncService.syncTestData("20240405");
//        syncService.syncTestData("20240406");
//        syncService.syncTestData("20240407");
//        syncService.syncTestData("20240408");
//        syncService.syncTestData("20240409");
//        syncService.syncTestData("20240410");
//        syncService.syncTestData("20240411");
//        syncService.syncTestData("20240412");
//        syncService.syncTestData("20240413");
//        syncService.syncTestData("20240414");
//        syncService.syncTestData("20240415");
//        syncService.syncTestData("20240416");
//        syncService.syncTestData("20240417");
//        syncService.syncTestData("20240418");
//        syncService.syncTestData("20240419");
//        syncService.syncTestData("20240420");
        syncService.syncTestData("20240421");
        syncService.syncTestData("20240422");
        syncService.syncTestData("20240423");
        syncService.syncTestData("20240424");
        syncService.syncTestData("20240425");
        syncService.syncTestData("20240426");
        syncService.syncTestData("20240427");
        syncService.syncTestData("20240428");
        syncService.syncTestData("20240429");
        syncService.syncTestData("20240430");
        syncService.syncTestData("20240501");
        syncService.syncTestData("20240502");
        syncService.syncTestData("20240503");
        syncService.syncTestData("20240504");
        syncService.syncTestData("20240505");
        syncService.syncTestData("20240506");
//        syncService.syncTestData(time);
//        syncService.syncTestData("20240402");
//        syncService.syncTestData("20240403");
//        syncService.syncTestData("20240404");
//        syncService.syncTestData("20240405");
//        syncService.syncTestData("20240406");
//        syncService.syncTestData("20240407");
//        syncService.syncTestData("20240408");

//        syncService.syncData("20240402");
//        syncService.syncData("20240403");
//        syncService.syncData("20240404");
//        syncService.syncData("20240405");
//        syncService.syncData("20240406");
//        syncService.syncData("20240407");
//        syncService.syncData("20240408");
//        syncService.syncData("20240409");
//        syncService.syncData("20240410");
//        syncService.syncData("20240411");
//        syncService.syncData("20240412");
//        syncService.syncData("20240413");
//        syncService.syncData("20240414");
//        syncService.syncData("20240415");
//        testBizService.generateSingleTestData(time);
    }

    @GetResource(name = "sync", path = "/sync-purchase", requiredLogin = false, requiredPermission = false)
    @ApiOperation("sync")
    @BusinessLog
    public void syncPurchase(@RequestParam("time") String time) throws IOException {
        //基础数据
//        syncService.syncData();
//        syncService.syncStoreData();
        //进销存数据
        syncService.syncDataPurchase("20240401");
        syncService.syncDataPurchase("20240402");
        syncService.syncDataPurchase("20240403");
        syncService.syncDataPurchase("20240404");
        syncService.syncDataPurchase("20240405");
        syncService.syncDataPurchase("20240406");
        syncService.syncDataPurchase("20240407");
        syncService.syncDataPurchase("20240408");
        syncService.syncDataPurchase("20240409");
        syncService.syncDataPurchase("20240410");
        syncService.syncDataPurchase("20240411");
        syncService.syncDataPurchase("20240412");
        syncService.syncDataPurchase("20240413");
        syncService.syncDataPurchase("20240414");
        syncService.syncDataPurchase("20240415");
//        testBizService.generateSingleTestData(time);
    }

    @GetResource(name = "同步基础数据", path = "/sync-base", requiredLogin = false, requiredPermission = false)
    @ApiOperation("同步基础数据")
    @BusinessLog
    public void syncBase(@RequestParam("time") String time) throws IOException {
        //基础数据
        syncService.syncData();
        syncService.syncStoreData();
//        进销存数据
//        syncService.syncData(time);
//        testBizService.generateSingleTestData(time);
    }

    @GetResource(name = "同步批号", path = "/sync/batch", requiredLogin = false, requiredPermission = false)
    @ApiOperation("同步基础数据")
    @BusinessLog
    public void syncBatch(@RequestParam("time") String time) throws IOException {
        //基础数据
        syncService.syncBatch(time);

    }


    @ResponseBody
    @PostResource(name = "图片上传", path = "/upload-img", requiredLogin = true, requiredPermission = true)
    @ApiOperation("图片上传 http://47.96.74.120:9091/static/ 图片前缀")
    @BusinessLog
    public ResponseData<String> uploadImg(MultipartFile file) throws IOException {
        log.info("12312321");
        String name = file.getOriginalFilename();
        UUID uuid = UUID.randomUUID();
        String substring = name.substring(name.lastIndexOf("."));
        String fileName = uuid + substring;
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filrUrl + "/" + fileName));
        return new SuccessResponseData<>(fileName);
    }


    @GetResource(name = "同步新的药德数据", path = "/sync/new/yaode", requiredLogin = false, requiredPermission = false)
    @ApiOperation("sync")
    public void syncNewYaode(@RequestParam("time") String time, @RequestParam("endTime") String endTime,
                             @RequestParam("tag") String tag) throws IOException {
        LocalDate parse = LocalDate.parse(time, SIMPLE_DATE_FORMAT1);
        log.info("开始同步数据time={},endTime={},tag={}", time, endTime, tag);

        while (true) {
            String format = parse.format(SIMPLE_DATE_FORMAT1);
            syncService.syncNewMaterialData(format, tag);
//            syncService.syncTestData(format);
            if (format.equals(endTime)) {
                break;
            }
            parse = parse.plusDays(1);
        }
    }

    @GetResource(name = "同步新的药德测试数据", path = "/sync/new/yaode/test", requiredLogin = false, requiredPermission = false)
    @ApiOperation("sync")
    public void syncNewYaodeTest(@RequestParam("time") String time, @RequestParam("endTime") String endTime) throws IOException {
        LocalDate parse = LocalDate.parse(time, SIMPLE_DATE_FORMAT1);
        log.info("开始同步数据time={},endTime={}", time, endTime);

        while (true) {
            String format = parse.format(SIMPLE_DATE_FORMAT1);
            syncService.syncNewTestData(format);
//            syncService.syncTestData(format);
            if (format.equals(endTime)) {
                break;
            }
            parse = parse.plusDays(1);
        }
    }


}
